package com.emellend.api.expandablelist;

import android.app.ExpandableListActivity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.widget.ExpandableListAdapter;
import android.widget.SimpleCursorTreeAdapter;

public class ExpandableList2 extends ExpandableListActivity {
    private int mGroupIdColumnIndex; 
    
    private String mPhoneNumberProjection[] = new String[] {
            Phone._ID, Phone.NUMBER
    };

    private ExpandableListAdapter mAdapter;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Cursor groupCursor = managedQuery(Phone.CONTENT_URI,
                new String[] {Phone._ID, Phone.DISPLAY_NAME}, null, null, null);

        mGroupIdColumnIndex = groupCursor.getColumnIndexOrThrow(Phone._ID);

        mAdapter = new MyExpandableListAdapter(groupCursor,
                this,
                android.R.layout.simple_expandable_list_item_1,
                android.R.layout.simple_expandable_list_item_1,
                new String[] {Phone.DISPLAY_NAME}, 
                new int[] {android.R.id.text1},
                new String[] {Phone.NUMBER}, 
                new int[] {android.R.id.text1});
        setListAdapter(mAdapter);
    }

    public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {

        public MyExpandableListAdapter(Cursor cursor, Context context, int groupLayout,
                int childLayout, String[] groupFrom, int[] groupTo, String[] childrenFrom,
                int[] childrenTo) {
            super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childrenFrom,
                    childrenTo);
        }

        @Override
        protected Cursor getChildrenCursor(Cursor groupCursor) {
            Uri withAppendedId =ContentUris.withAppendedId(Phone.CONTENT_URI,  
            						groupCursor.getLong(mGroupIdColumnIndex));
            return managedQuery(withAppendedId, mPhoneNumberProjection, null, null, null);
        }

    }
}

